package amazon

import (
	"black_mamba/global"
	"black_mamba/pages"
	"black_mamba/workers"
	_ "embed"
	"fmt"
	"gitee.com/wengo/windows_gui/widget"
	"gitee.com/wengo/windows_gui/xc"
	"strconv"
	"sync"
	"time"
	"unsafe"
)

type RegisterPage struct {
	pages.Foundation
	style        map[string]int
	taskTotal    *widget.ShapeText
	detailLayout *widget.LayoutEle
}

func NewRegisterPage() *RegisterPage {
	registerPage := &RegisterPage{
		Foundation: pages.Foundation{
			ExecuteBtn: widget.NewButtonByName("registerExecuteBtn"),
			LogEdit:    widget.NewEditByName("registerLogEdit"),
			Style:      nil,
			Topic:      "register",
			//ListBoxLayout: widget.NewLayoutEleByName("registerListBoxLayout"),
			//ParentLayout:  widget.NewLayoutEleByName("registerParentLayout"),
		},
		taskTotal: widget.NewShapeTextByName("registerTaskTotal"),
	}

	// 绑定执行按钮事件
	registerPage.ExecuteBtn.Event_BnClick(registerPage.execute)

	// 设置log样式
	registerPage.SetEditStyle()

	// 创建listbox
	registerPage.NewListBox("registerListBox", "register_list.xml")

	//绑定所有订阅
	//绑定所有订阅
	registerPage.Subscribes()
	registerPage.customSubscribes()

	// 设置listbox的按钮事件
	//registerPage.ListBox.RegEventC(xcc.XE_LISTBOX_TEMP_CREATE_END, func(pItem *xc.ListBox_Item_, nFlag int, pbHandled *bool) int {
	//	itemViewBtn := widget.NewButtonByHandle(registerPage.ListBox.GetTemplateObject(int(pItem.Index), 1))
	//	itemViewBtn.Event_BnClick(func(pbHandled *bool) int {
	//		index := registerPage.ListBox.GetItemIndexFromHXCGUI(itemViewBtn.Handle)
	//		asin := registerPage.ListBox.GetItemText(index, 1)
	//		wapi.ShellExecuteW(1, "open", `C:\Program Files\Google\Chrome\Application\chrome.exe`, fmt.Sprintf("https://www.amazon.com/dp/%s", asin), "", 3)
	//		return 0
	//	})
	//	return 0
	//})
	return registerPage
}

//注册所有订阅者
func (b *RegisterPage) customSubscribes() {

	addData := b.AddData
	_ = global.BM_EVENTBUS.Subscribe(fmt.Sprintf("%s:addData", b.Topic), func(data map[string]interface{}) {
		xc.XC_CallUiThread(addData, int(uintptr(unsafe.Pointer(&data))))
	})

	updateData := b.UpdateData
	_ = global.BM_EVENTBUS.Subscribe(fmt.Sprintf("%s:updateData", b.Topic), func(data map[string]interface{}) {
		xc.XC_CallUiThread(updateData, int(uintptr(unsafe.Pointer(&data))))
	})

	deleteData := b.DeleteData
	_ = global.BM_EVENTBUS.Subscribe(fmt.Sprintf("%s:deleteData", b.Topic), func(data string) {
		xc.XC_CallUiThread(deleteData, int(uintptr(unsafe.Pointer(&data))))
	})
}

/* 事件回调 */
func (b *RegisterPage) execute(pbHandled *bool) int {
	*pbHandled = true

	if global.BM_CONFIG.Section("basic").Key("serialNumberCiphertext").Value() == "" {
		b.UpdateLog(int(uintptr(unsafe.Pointer(&(map[string]string{"status": "error", "content": "请先设置机器序列号"})))))
		return 0
	}

	if global.BM_CONFIG.Section("proxy").Key("username").Value() == "" {
		b.UpdateLog(int(uintptr(unsafe.Pointer(&(map[string]string{"status": "error", "content": "请先设置代理用户名"})))))
		return 0
	}

	if global.BM_CONFIG.Section("proxy").Key("password").Value() == "" {
		b.UpdateLog(int(uintptr(unsafe.Pointer(&(map[string]string{"status": "error", "content": "请先设置代理密码"})))))
		return 0
	}

	//重绘父
	b.ToggleBtn(int(uintptr(unsafe.Pointer(b.ExecuteBtn))))

	go func() {

		tableData := map[string]interface{}{
			"action":  "add",
			"headers": []string{"name", "password", "email", "status"},
			"body":    []map[string]string{},
		}

		var taskWg sync.WaitGroup
		var chans []chan interface{}

		ticker := time.NewTicker(1 * time.Second)
		for {
			<-ticker.C
			if global.BM_POOL.Running() < 1 {
				registerUser, err := global.BM_API.GetRegisterAccount(global.BM_CONFIG.Section("basic").Key("serialNumberCiphertext").Value())
				if err != nil {

				} else {
					var body []map[string]string
					body = append(body, map[string]string{
						"name":     registerUser.Name,
						"password": registerUser.Password,
						"email":    registerUser.Email,
					})

					tableData["body"] = body

					global.BM_EVENTBUS.Publish("register:addData", tableData)

					registerWorker := workers.NewRegisterWorker()
					var ch = make(chan interface{})
					chans = append(chans, ch)
					err := global.BM_POOL.Submit(registerWorker.Decorator(registerWorker.Execute, map[string]interface{}{
						"registerUser": registerUser,
					}, &taskWg, nil))

					if err != nil {

					}
				}
			}
		}

		taskWg.Wait()

		//registerWorker := workers.NewRegisterWorker()
		//registerWorker.Execute(nil)

		//tableData := map[string]interface{}{
		//	"headers": []string{"id", "asin", "seller_id", "total"},
		//	"body":    []map[string]string{},
		//}

		//for {
		//
		//	// 获取任务
		//	data := global.BM_API.GetTaskList(global.BM_CONFIG.Section("basic").Key("serialNumberCiphertext").Value()) // 美国
		//
		//	if gjson.Get(data, "status").String() != "success" {
		//		global.BM_EVENTBUS.Publish("register:log", map[string]string{"status": "info", "content": "暂无任务需要执行, 暂停1分钟再请求"})
		//		//xc.XC_CallUiThread(updateLog, int(uintptr(unsafe.Pointer(&(map[string]string{"status": "info", "content": "暂无任务需要执行, 暂停1分钟再请求"})))))
		//		time.Sleep(1 * time.Minute)
		//		continue
		//	}
		//
		//	global.BM_EVENTBUS.Publish("register:clearLog")
		//	global.BM_EVENTBUS.Publish("register:log", map[string]string{"status": "success", "content": "成功获取任务"})
		//	global.BM_EVENTBUS.Publish("register:taskTotal", map[string]int{"taskGroupTotal": int(gjson.Get(data, "data.task_group_total.value").Int()), "taskTotal": int(gjson.Get(data, "data.task_total.value").Int())})
		//
		//	delay := gjson.Get(data, "data.machine.executeTimeout.value").Int()
		//	//delay = 0
		//	var body []map[string]string
		//	for _, task := range gjson.Get(data, "data.tasks").Array() {
		//		for _, d := range gjson.Get(task.String(), "list").Array() {
		//			id := gjson.Get(d.String(), "task_id.value").String()
		//			asin := gjson.Get(d.String(), "asin.value").String()
		//			sellerId := gjson.Get(d.String(), "seller_id.value").String()
		//			body = append(body, map[string]string{
		//				"id":        id,
		//				"asin":      asin,
		//				"seller_id": sellerId,
		//			})
		//		}
		//	}
		//
		//	tableData["body"] = body
		//
		//	// 更新列表
		//	global.BM_EVENTBUS.Publish("register:updateTable", tableData)
		//
		//	registerWorker := workers.NewRegisterWorker()
		//	var taskWg sync.WaitGroup
		//	var chans []chan interface{}
		//	for _, task := range gjson.Get(data, "data.tasks").Array() {
		//		for i := 0; i <= 10; i++ {
		//			list := task.String()
		//			var ch = make(chan interface{})
		//			chans = append(chans, ch)
		//			err := global.BM_POOL.Submit(registerWorker.Decorator(registerWorker.Execute, map[string]interface{}{
		//				"tasks": list,
		//			}, &taskWg, ch))
		//			if err != nil {
		//				return
		//			}
		//		}
		//
		//		//break
		//	}
		//
		//	taskWg.Wait()
		//
		//	global.BM_EVENTBUS.Publish("register:log", map[string]string{"status": "success", "content": "================ 开始统计 =================="})
		//
		//	// 获取协程返回的数据
		//	for _, ch := range chans {
		//		chResult := <-ch
		//		if chResult != nil {
		//			result := chResult.(map[string]string)
		//			if len(result) > 0 {
		//				global.BM_EVENTBUS.Publish("register:log", result)
		//			}
		//		}
		//	}
		//
		//	global.BM_EVENTBUS.Publish("register:log", map[string]string{"status": "success", "content": "================ 统计结束 =================="})
		//	global.BM_EVENTBUS.Publish("register:log", map[string]string{"status": "info", "content": fmt.Sprintf("等待 %d 分钟进行下一轮任务", delay)})
		//
		//	time.Sleep(time.Duration(delay) * time.Minute)
		//
		//}

		xc.XC_CallUiThread(b.ToggleBtn, int(uintptr(unsafe.Pointer(b.ExecuteBtn))))

	}()

	return 0
}

func (b *RegisterPage) AddData(data int) int {
	tableData := *(*map[string]interface{})(unsafe.Pointer(uintptr(data)))

	// 填充头部
	headers := tableData["headers"].([]string)

	for _, header := range headers {
		xc.XAdTable_AddColumn(b.HAdapter, header)
	}

	// 填充body
	body := tableData["body"].([]map[string]string)
	for _, bd := range body {
		item := xc.XAdTable_AddItemText(b.HAdapter, "")
		for index, header := range headers {
			xc.XAdTable_SetItemText(b.HAdapter, item, index, bd[header])
		}
	}

	b.RedrawListBoxLayout()
	return 0
}

func (b *RegisterPage) UpdateData(data int) int {
	tableData := *(*map[string]interface{})(unsafe.Pointer(uintptr(data)))
	email := tableData["email"].(string)
	info := tableData["info"].(string)
	count := xc.XAdTable_GetCount(b.HAdapter)

	for i := 0; i < count; i++ {
		if xc.XAdTable_GetItemText(b.HAdapter, i, 2) == email {
			xc.XAdTable_SetItemText(b.HAdapter, i, 3, info)
			break
		}
	}

	b.RedrawListBoxLayout()
	return 0
}

func (b *RegisterPage) DeleteData(data int) int {
	email := *(*string)(unsafe.Pointer(uintptr(data)))

	count := xc.XAdTable_GetCount(b.HAdapter)
	for i := 0; i < count; i++ {
		if xc.XAdTable_GetItemText(b.HAdapter, i, 2) == email {
			xc.XAdTable_DeleteItem(b.HAdapter, i)
			break
		}
	}

	b.RedrawListBoxLayout()
	return 0
}

func (b *RegisterPage) updateTaskTotal(data int) int {
	result := *(*map[string]int)(unsafe.Pointer(uintptr(data)))
	b.taskTotal.SetText(fmt.Sprintf("当前任务组总数为: %d, 任务总数为: %d", result["taskGroupTotal"], result["taskTotal"]))
	b.taskTotal.Redraw()
	widget.NewLayoutEleByHandle(b.taskTotal.GetParentEle()).AdjustLayout(0)
	widget.NewLayoutEleByHandle(b.taskTotal.GetParentEle()).Redraw(true)

	return 0
}

func (b *RegisterPage) updateFeedBack(feedback int) int {
	data := *(*map[interface{}]uint)(unsafe.Pointer(uintptr(feedback)))
	count := b.ListBox.GetCount_AD()
	if count > 0 {
		for iitem := 0; iitem < count; iitem++ {
			asin := b.ListBox.GetItemText(iitem, 1)
			val, ok := data[asin]
			if ok {
				curTotal, _ := strconv.Atoi(b.ListBox.GetItemText(iitem, 1))
				curTotal += int(val)
				xc.XAdTable_SetItemText(b.HAdapter, iitem, 3, strconv.Itoa(curTotal))
			}

		}
	}

	b.RedrawListBoxLayout()

	return 0
}
